package com.kos.backend.service.impl.user.snake;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kos.backend.mapper.SnakeMapper;
import com.kos.backend.pojo.Snake;
import com.kos.backend.pojo.User;
import com.kos.backend.service.impl.utils.UserDetailsImpl;
import com.kos.backend.service.user.snake.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AddServiceImpl implements AddService {

    @Autowired
    private SnakeMapper snakeMapper;

    @Override
    public Map<String, String> add(Map<String, String> data) {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();
        String title = data.get("title");
        String description = data.get("description");
        String content = data.get("content");
        Map<String,String> map = new HashMap<>();

        if(title == null || title.length() == 0){
            map.put("error_message","标题不能为空");
            return map;
        }
        if(title.length() > 255){
            map.put("error_message","标题长度过长,不能超过255");
            return map;
        }
        if(description == null || description.length() == 0){
            description = "这个用户很懒，什么都没有写";
        }
        if(description.length() > 255){
            map.put("error_message","描述长度过长，长度不能超过255");
            return map;
        }
        if(content == null || content.length() == 0){
            map.put("error_message","代码不能为空");
            return map;
        }
        if(content.length() > 10000){
            map.put("error_message","代码过长，不能超过10000");
            return map;
        }

        QueryWrapper<Snake> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        if(snakeMapper.selectCount(queryWrapper) >= 10){
            map.put("error_message","每个用户最多只能添加10条蛇");
            return map;
        }

        Date now = new Date();
        Snake snake = new Snake(null,user.getId(),title,description,content,now,now);
        snakeMapper.insert(snake);
        map.put("error_message","success");
        return map;
    }
}
